//
//  MultiTimerViewController.m
//  MultiTimer
//
//  Created by Jeffrey Palm on 6/3/09.
//  Copyright Jeffrey Palm 2009. All rights reserved.
//

#import "MultiTimerViewController.h"
#import <AudioToolbox/AudioToolbox.h>

#define kUnsetTimer -1
#define kAlarmSleep 0.5

@interface MultiTimerViewController (PrivateMethods)
- (void)tick:(id)param;
- (NSString*)pad:(int)i;
@end


@implementation MultiTimerViewController

@synthesize timePicker;
@synthesize toolbar;
@synthesize startButton;
@synthesize resetButton;
@synthesize setButton;
@synthesize unsetButton;
@synthesize mainTimerButton;
@synthesize timerButton1;
@synthesize timerButton2;
@synthesize timerButton3;
@synthesize timerButton4;
@synthesize timerButton5;
@synthesize timeLabel;

@synthesize clock;
@synthesize ticking;

@synthesize timer;

@synthesize soundFileURLRef;
@synthesize soundFileObject;

@synthesize currentButtonIndex;

// ----------------------------------------------------------------------------------
// Array properties
// ----------------------------------------------------------------------------------

-(int*)alarms {
	return _alarms;
}

-(UIBarButtonItem**)timerButtons {
	return _timerButtons;
}

// ----------------------------------------------------------------------------------
// Misc
// ----------------------------------------------------------------------------------

- (void)setTitleForAllStates:(UIButton*)b withTitle:(NSString*)title {
	UIControlState states[6] = {
		UIControlStateNormal,
    UIControlStateHighlighted,
    UIControlStateDisabled,
    UIControlStateSelected,
    UIControlStateApplication,
    UIControlStateReserved
	};
	for (int i=0; i<6; i++) {
		[b setTitle:title forState:states[i]];
	}
}

-(void)startTicking {
	NSLog(@"start ticking");
	if ([[timeLabel text] isEqualToString:@"00:00:00"]) {
		[self resetTimer:nil];
	}
	timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick:) userInfo:nil repeats:YES];	
	ticking = YES;
	[self setTitleForAllStates:startButton withTitle:@"Stop"];
}

-(void)stopTicking {
	NSLog(@"stop ticking");
	[timer invalidate];
	ticking = NO;
	[self setTitleForAllStates:startButton withTitle:@"Start"];
}

- (void)vibrate {
	NSLog(@"vibrate");
 	AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);		
}
	
- (void)playAlarm {
	NSLog(@"play alarm");
	AudioServicesPlaySystemSound (self.soundFileObject);
	[self vibrate];
	[NSThread sleepForTimeInterval:kAlarmSleep];
	[self vibrate];
}
	
- (void)updateTimeLabel:(int)hours andMinutes:(int)minutes andSeconds:(int)seconds {
	NSString *timeString = [NSString stringWithFormat:@"%@:%@:%@", [self pad:hours], [self pad:minutes], [self pad:seconds]];
	[[self timeLabel] setText:timeString];	
}
	
- (void)tick:(id)param {
	BOOL done = [clock tick];
	int seconds = [clock time];
	int hours			= seconds	/	3600;
	int rem				= seconds	%	3600;
	int minutes		= rem			/		60;	
	int secs			= rem			%		60;
	[self updateTimeLabel:hours andMinutes:minutes andSeconds:secs];
	
	// Check to see if we're at an intermediate alarm
	for (int i=1; i<=NUM_TIMERS; i++) {
		int alarm = [self alarms][i];
		if (alarm == seconds) {
			[self vibrate];
		}
	}
	
	// Check to see if we're done
	if (done) {
		[self stopTicking];
		[self playAlarm];
	}

}
	

// ----------------------------------------------------------------------------------
// Timer interaction
// ----------------------------------------------------------------------------------

-(IBAction)toggleTimer:(id)sender {
	NSLog(@"toggleTimer");
	if (ticking) {
		[self stopTicking];
	} else {
		[self startTicking];
	}
}

-(IBAction)resetTimer:(id)sender {
	int startTime = [self alarms][0];
	int hours			= startTime	/	3600;
	int rem				= startTime	%	3600;
	int minutes		= rem				/		60;
	[clock resetTime:hours andMinutes:minutes];
	[self updateTimeLabel:hours andMinutes:minutes andSeconds:0];
	
}

-(IBAction)setCurrentTimer:(id)sender {
	NSLog(@"setCurrentTimer");	
	NSDate *date = [[self timePicker] date]; 
	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
	[formatter setTimeStyle:NSDateFormatterMediumStyle];	// 2:44:55 PM
	NSString *dateString = [formatter stringFromDate:date];
	//
	// Remove the ' '
	//
	NSString *justTime = (NSString*)[[dateString componentsSeparatedByString:@" "] objectAtIndex:0];
	NSString *amPm = (NSString*)[[dateString componentsSeparatedByString:@" "] objectAtIndex:1];
	//
	// Divide the time into hours, minutes, seconds
	//
	NSArray *parts = [justTime componentsSeparatedByString:@":"];
	int hours		= [[parts objectAtIndex:0] intValue];
	if ([amPm isEqualToString:@"PM"]) {
		if (hours != 12) {
			hours += 12;
		}
	} else if (hours == 12) {
		hours = 0;
	}
	int minutes = [[parts objectAtIndex:1] intValue];
	int seconds = [[parts objectAtIndex:2] intValue];
	NSLog(@"date=%@ hours=%i minutes=%i seconds=%i", dateString, hours, minutes, seconds);
	int totalSeconds = seconds + 60*minutes + 60*60*hours;
	[self alarms][currentButtonIndex] = totalSeconds;
	NSLog(@"Using timer number %i", currentButtonIndex);
}

-(IBAction)unsetCurrentTimer:(id)sender {
	NSLog(@"unsetCurrentTimer");	
	[self alarms][currentButtonIndex] = kUnsetTimer;
}

-(NSString*)pad:(int)i {
	if (i<10) {
		return [NSString stringWithFormat:@"0%i", i];
	}
	return [NSString stringWithFormat:@"%i", i];
}

-(BOOL)setPicker:(int)seconds {
	if (seconds < 0) {
		return NO;
	}
	int hours		= seconds/3600;
	int rem			= seconds%3600;
	int minutes = rem/60;
	NSString *amPm;
	if (hours == 0) {
		amPm = @"AM";
		hours = 12;
	} else if (hours > 12) {
		amPm = @"PM";
		hours -= 12;
	} else {
		amPm = @"AM";
	}
	NSString *dateString = [NSString stringWithFormat:@"%i:%@:00 %@", hours, [self pad:minutes], amPm];
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"hh:mm:ss a"];	
	NSDate *date = [dateFormat dateFromString:dateString];
	[[self timePicker] setDate:date];
	return YES;
}

-(void)useTimer:(int)index {
	NSLog(@"Using timer %i",index);
	int alarmSeconds = [self alarms][index];
	[self setPicker:alarmSeconds];
	currentButtonIndex = index;
}

-(IBAction)useMainTimer:(id)sender {
	NSLog(@"useMainTimer");
	[self useTimer:0];
}

-(IBAction)useTimer1:(id)sender {
	NSLog(@"useTimer1");
	[self useTimer:1];
}

-(IBAction)useTimer2:(id)sender {
	NSLog(@"useTimer2");
	[self useTimer:2];
}

-(IBAction)useTimer3:(id)sender {
	NSLog(@"useTimer3");
	[self useTimer:3];
}

-(IBAction)useTimer4:(id)sender {
	NSLog(@"useTimer4");
	[self useTimer:4];
}

-(IBAction)useTimer5:(id)sender {
	NSLog(@"useTimer5");
	[self useTimer:5];
}

-(void)unsetButton:(UIBarButtonItem*)item atIndex:(int)index {
	NSLog(@"Unset %@ at %i", item, index);
	if (item != mainTimerButton) {
		[[self timerButtons][index] setTitle:@"Unset"];
	}
	[self alarms][index] = kUnsetTimer;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	currentButtonIndex = 0;
	clock = [[Clock alloc] init];
	[self unsetButton:mainTimerButton atIndex:0];
	[self unsetButton:timerButton1		atIndex:1];
	[self unsetButton:timerButton2		atIndex:2];
	[self unsetButton:timerButton3		atIndex:3];
	[self unsetButton:timerButton4		atIndex:4];
	[self unsetButton:timerButton4		atIndex:5];
	[self useTimer:0];
	
	// Get the main bundle for the app
	CFBundleRef mainBundle;
	mainBundle = CFBundleGetMainBundle ();
	
	// Get the URL to the sound file to play
	soundFileURLRef  =	CFBundleCopyResourceURL (
																							 mainBundle,
																							 CFSTR ("beep-7"),
																							 CFSTR ("wav"),
																							 NULL
																							 );
	
	// Create a system sound object representing the sound file
	AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
}

- (void)changeButtonImage:(UIButton*)button {
	UIImage *buttonBackground = [UIImage imageNamed:@"whiteButton.png"];
	UIImage *buttonBackgroundPressed = [UIImage imageNamed:@"blueButton.png"];
	
	UIImage *newImage = [buttonBackground stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
	[button setBackgroundImage:newImage forState:UIControlStateNormal];
	
	UIImage *newPressedImage = [buttonBackgroundPressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
	[button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];
	
}

- (void) loadView {
	NSLog(@"loadView");
	[super loadView];
	[self changeButtonImage:startButton];
	[self changeButtonImage:resetButton];
	[self changeButtonImage:setButton];
	[self changeButtonImage:unsetButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)dealloc {
    [super dealloc];
}

@end
